
<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8">
		<title>商品详细-聚码网-站长交易平台</title>
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
		<link rel="stylesheet" href="./public/static/index/bui/bui.css">
		<script src="./public/static/index/bui/zepto.js"></script>
		<script src="./public/static/index/bui/bui.js"></script>
		<!-- 添加图标字体支持 -->
		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
		<!-- 聊天在线状态管理 -->
		<script src="./public/static/index/js/chat-status.js"></script>
		
		<link rel="icon" href="./public/uploads/20251011/caae188ad173fbe811bdfb2f5fe0a5ce.jpg">
		<style>
		/* 图标字体样式 */
		.icon-home:before {
		    content: "\f015";
		    font-family: FontAwesome;
		}
		.icon-edit:before {
		    content: "\f044";
		    font-family: FontAwesome;
		}
		.icon-chat:before {
		    content: "\f075";
		    font-family: FontAwesome;
		}
		/* 确保图标显示 */
		[class^="icon-"], [class*=" icon-"] {
		    font-family: FontAwesome;
		    font-style: normal;
		    font-weight: normal;
		    display: inline-block;
		    text-decoration: inherit;
		}
        html, body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            background-color: #fff;
        }
        body {
            padding-bottom: 60px; /* 为底部导航留出空间 */
            overflow-x: hidden;
        }
        .bui-page {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }
        main {
            flex: 1;
            width: 100%;
            overflow-y: auto;
            overflow-x: hidden;
            -webkit-overflow-scrolling: touch;
            padding-bottom: 10px;
        }
        footer {
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            background-color: #fff;
            z-index: 1000;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
            border-top: 1px solid #f0f0f0;
        }
        footer .bui-nav {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 8px 5px;
            margin: 0;
            list-style: none;
            height: 50px;
        }
        footer .bui-nav > div {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        footer .bui-nav > div li {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 4px 8px;
            margin: 0;
            background-color: transparent;
            border: none;
        }
        footer .bui-nav > div li i {
            font-size: 20px;
            color: #333;
            margin-bottom: 2px;
        }
        footer .bui-nav > div li a {
            font-size: 11px;
            color: #333;
            text-decoration: none;
            line-height: 1.2;
        }
        footer .bui-nav > div li.active i,
        footer .bui-nav > div li.active a {
            color: #ff0057;
        }
        #contactService {
            padding: 10px 20px !important;
            font-size: 15px !important;
            min-width: 120px;
            height: auto !important;
            line-height: 1.4;
            border-radius: 20px !important;
            background-color: #ff0057 !important;
            color: #fff !important;
            font-weight: bold;
            margin: 0;
        }
            .bui-list-pic .bui-pic img, .bui-list-photo .bui-thumbnail img {
                width: 100%;
                height: 175px;
            }
            hr {
                background: #f3f5f8;
                border: 0;
                padding: 0;
                margin: 0;
                display: block;
                height: 1px;
                width: 100%;
            }
            .bui-slide {
                height: 375px;
                position: relative;
                overflow: hidden;
            }
            .bui-slide .bui-slide-main {
                height: 100%;
                overflow: hidden;
                position: relative;
            }
            .bui-slide .bui-slide-main>ul {
                height: 100%;
                display: flex;
                margin: 0;
                padding: 0;
                list-style: none;
                transition: transform 0.3s ease;
                transform: translateX(0);
            }
            .bui-slide .bui-slide-main>ul>li {
                height: 100%;
                flex: 0 0 100%;
                width: 100%;
            }
            .bui-slide .bui-slide-main>ul>li img {
                max-width: 100%;
                width: 100%;
                height: 100%;
                object-fit: cover;
                display: block;
            }
            /* 轮播图指示点样式 */
            .bui-slide-head {
                position: absolute;
                bottom: 10px;
                left: 50%;
                transform: translateX(-50%);
                z-index: 10;
                display: flex;
                gap: 8px;
            }
            .bui-slide-head span {
                width: 8px;
                height: 8px;
                border-radius: 50%;
                background-color: rgba(255, 255, 255, 0.5);
                display: inline-block;
                cursor: pointer;
                transition: background-color 0.3s;
            }
            .bui-slide-head span.active {
                background-color: #fff;
                width: 20px;
                border-radius: 4px;
            }.bui-table th, .bui-table td {
     border: 0px solid #ddd; 
    padding: .1rem;
    color: #666;
    font-weight: normal;
    font-size: .28rem;
    background: #fff;
    padding: .25rem .1rem;
}
        </style>
	</head>
	<body style="background-color: #fff;">
        
<div class="bui-page">
    <!-- <header class="bui-bar" style="background: linear-gradient(45deg,#ffffff,#ffffff,#ffffff);">
		<div class="bui-bar-left" >
			<a class="bui-btn btn-back" onclick="bui.back();"><i class="icon-back" style="color: #000;"></i></a>
		</div>
		<div class="bui-bar-main"></div>
		<div class="bui-bar-right">
			<a onclick="fx()" class="bui-btn">
                <i class="icon" style="color: #000;">&#xe62e</i>
            </a>
		</div>
	</header> -->
	<main>
        <div id="slide" class="bui-slide">
            <div class="bui-slide-main">
              <ul id="goodsImages">
                <li>
                  <img src="" alt="加载中...">
                </li>
              </ul>
            </div>
            <div class="bui-slide-head">
                <!-- 指示点将动态生成 -->
            </div>
          </div><hr style="height: 5px;">
          <div style="margin-top: 5px;">
          <div id="goodsPriceSection" style="padding: 15px 12px;
    width: 97%;
    margin: 0 auto;
    border-radius: 8px;
    background: linear-gradient(135deg, #ff4757 0%, #ff3838 100%);
    color:#fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 8px rgba(255, 71, 87, 0.3);
    ">
            <!-- 左侧：价格信息 -->
            <div style="flex: 1;">
                <div style="display: flex; align-items: baseline; margin-bottom: 6px;">
                    <span style="color: #ffffff;font-weight: bold;font-size: 12px;">¥</span>
                    <span style="color: #ffffff;font-weight: bold;font-size: 28px;line-height: 1;" id="goodsDiscount">加载中...</span>
                    <span id="goodsAmountContainer" style="color: rgba(255,255,255,0.7);font-size: 14px;text-decoration: line-through;margin-left: 8px;font-weight: normal;">¥<span id="goodsAmount">--</span></span>
                </div>
                <div style="color: rgba(255,255,255,0.9);font-size: 12px;">
                    <span>已售</span><span id="goodsSales">--</span>
                </div>
            </div>
            
            <!-- 右侧：促销标签 -->
            <div style="text-align: right;padding-left: 15px;border-left: 1px dashed rgba(255,255,255,0.3);">
                <div style="display: flex; align-items: center; justify-content: flex-end; margin-bottom: 4px;">
                    <span style="font-size: 18px; margin-right: 4px;">⚡</span>
                    <span style="color: #ffffff;font-weight: bold;font-size: 16px;">百亿补贴</span>
                </div>
                <div style="color: rgba(255,255,255,0.85);font-size: 11px;line-height: 1.3;">
                    全网低价 售后无忧
                </div>
            </div>
        </div>
        <p style="margin-left: 15px;font-size: 25px;font-weight: bolder;color: black;margin-top: 10px;" id="goodsName">加载中...</p>
         <hr style="height: 5px;">
         
  <!--      <div style="width: 97%;-->
  <!--  margin: 0 auto;">-->
  <!--    	<div style="margin: 10px 20px 2px 20px;"><font style="font-weight: bolder;color:#000">官方</font><img src="/public/images/xq.png" style="height: 18px;margin-bottom: 3px;margin-right: 6px;vertical-align:middle;">-->
		<!--<span style="color: #CB7947">正品保障·损坏包赔·七天无理由</span></div>-->
  <!--          <div style="margin: 10px 20px 2px 20px;"><font style="font-weight: bolder;color:#000">保障</font><img src="/public/images/xq.png" style="height: 18px;margin-bottom: 3px;margin-right: 6px;vertical-align:middle;">-->
		<!--			<span style="color: #CB7947">基地甄选 · 品质保障 · 售后无忧</span></div>-->
					
		<!--		  <div style="margin: 1px 20px 10px 20px;">-->
  <!--          <p style="margin-top: 3px;"><font style="font-weight: bolder;color:#000">物流</font><font style="color: #666;margin-left: 15px;font-size: 15px;"></font></p>-->
  <!--      </div>-->
  <!--     </div>-->
         <hr style="height: 5px;">
        <!--<ul class="bui-list" id="commentGo">-->
        <!--  <li class="bui-btn bui-box">-->
        <!--      <div class="span1 " style="font-size: 15px;font-weight: bolder;color: black;">商品评价(0)</div>-->
        <!--      <div class="item-text">查看全部</div>-->
        <!--      <i class="icon-listright"></i>-->
        <!--  </li>-->
        <!--  <ul class="bui-list status-lists">-->
        <!--    <li class="bui-btn bui-box">-->
        <!--      <div class="icon status-pic">-->
        <!--          <img  src="" onerror=this.style.display="none" alt=""  />-->
        <!--      </div>-->
        <!--      <div class="span1">-->
        <!--          <h3 class="item-title status-title"></h3>-->
        <!--          <p class="details-content"></p>-->
        <!--      </div>-->
        <!--  </li>-->
        <!--</ul>-->
        <!--  </ul>-->
          <hr style="height: 5px;">
        <p style="margin: 10px;font-size: 15px;font-weight: bolder;color: black;">商品详细</p>
        <div style="padding: 10px; margin-bottom: 10px;">
            <table class="bui-table"  border="0" cellpadding="0" cellspacing="0"  frame="void" id="goodsDetails">
                            <tr>
                <th style="width: 25%;">描述</th>
                <td id="goodsDescription">加载中...</td>
              </tr>
                          </table>
        </div>
        <div id="goodsDetailImages">
                <!-- 商品详情图片将动态加载 -->
        </div>
        	</main>
	<footer>
		<ul id="tabFootNav" class="bui-nav">
		    <div>
            <li class="bui-btn bui-box-vertical">
                <i class="icon-home"></i>
                <a href="./index.html">进店</a>
            </li>
            <li class="bui-btn bui-box-vertical">
                <i class="icon-edit"></i>
                <a href="./orderQuery.html">订单</a>
            </li>
            <li class="bui-btn bui-box-vertical">
                <i class="icon-chat"></i>
                <a id="kflinksGo" href="javascript:void(0);">客服</a>
            </li>
            </div>
            <li style="padding: 0; margin-left: auto;">
                <div id="contactService" class="bui-btn">
                    联系客服购买
                </div>
            </li>
        </ul>
	</footer>
</div>

<!-- 全屏弹出框	 -->
<div id="dialogFull" class="bui-dialog" style="display: none;">
  <div class="bui-dialog-main">
      <img id="imgid" src=""  width="100%" height="100%">
  </div>
  <div class="bui-dialog-foot">
      <div class="bui-box">
          <div class="span1">
            <input type="hidden" id="urlinput" />
              <div class="bui-btn blue" id="closedislog">确定</div>
          </div>
      </div>
  </div>
</div>


<script>
// 商品详情API地址
var API_BASE_URL = "https://api.sc123.shop/";

// 设置聊天状态管理的API地址
if (window.ChatStatus) {
    window.ChatStatus.setApiBaseUrl(API_BASE_URL);
}
var GOODS_DETAIL_API = API_BASE_URL + "/api/v1/index/goods_detail";

// 获取URL参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}

// 加载商品详情
function loadGoodsDetail() {
    var goodsId = getUrlParam('id');
    if (!goodsId) {
        console.error("未找到商品ID");
        $("#goodsName").text("商品ID错误");
        return;
    }
    
    console.log("开始加载商品详情，商品ID:", goodsId);
    
    // 显示加载提示
    $("#goodsName").text("加载中...");
    $("#goodsDiscount").text("--");
    
    // 使用原生XHR请求（不依赖zepto）
    var xhr = new XMLHttpRequest();
    xhr.open('POST', GOODS_DETAIL_API + '?id=' + goodsId, true);
    xhr.timeout = 10000;
    
    xhr.onload = function() {
        console.log("XHR请求完成，状态码:", xhr.status);
        if (xhr.status >= 200 && xhr.status < 300) {
            try {
                var response = JSON.parse(xhr.responseText);
                console.log("商品详情数据:", response);
                if (response && response.code === 200 && response.data) {
                    renderGoodsDetail(response.data);
                } else {
                    console.error("获取商品详情失败:", response);
                    $("#goodsName").text("加载失败: " + (response.msg || "未知错误"));
                }
            } catch (e) {
                console.error("解析JSON失败:", e, xhr.responseText);
                $("#goodsName").text("数据解析失败");
            }
        } else {
            console.error("请求失败，状态码:", xhr.status);
            $("#goodsName").text("请求失败，错误码: " + xhr.status);
        }
    };
    
    xhr.onerror = function() {
        console.error("XHR请求出错");
        $("#goodsName").text("网络错误，请检查网络连接");
    };
    
    xhr.ontimeout = function() {
        console.error("XHR请求超时");
        $("#goodsName").text("请求超时，请稍后重试");
    };
    
    xhr.send();
}

// 简单的原生滑动实现（备用方案）
function initSimpleSlide() {
    var slideContainer = document.querySelector("#slide .bui-slide-main");
    var slideList = document.querySelector("#goodsImages");
    if (!slideContainer || !slideList) return;
    
    var currentIndex = 0;
    var images = slideList.querySelectorAll("li");
    var totalImages = images.length;
    
    if (totalImages <= 1) {
        // 只有一张图片时隐藏指示点
        $("#slide .bui-slide-head").hide();
        return;
    }
    
    // 确保样式已设置（虽然CSS已经设置了，但这里再次确认）
    slideList.style.display = "flex";
    slideList.style.transition = "transform 0.3s ease";
    slideList.style.transform = "translateX(0)";
    slideContainer.style.overflow = "hidden";
    images.forEach(function(img) {
        img.style.flex = "0 0 100%";
        img.style.width = "100%";
        img.style.height = "100%";
    });
    
    // 更新指示点
    function updateDots(index) {
        $("#slide .bui-slide-head span").removeClass("active");
        $("#slide .bui-slide-head span").eq(index).addClass("active");
    }
    
    // 触摸滑动支持
    var startX = 0;
    var currentX = 0;
    var isDragging = false;
    
    // 移除之前的事件监听器（如果存在）
    var newContainer = slideContainer.cloneNode(true);
    slideContainer.parentNode.replaceChild(newContainer, slideContainer);
    slideContainer = newContainer;
    slideList = slideContainer.querySelector("#goodsImages");
    
    slideContainer.addEventListener("touchstart", function(e) {
        startX = e.touches[0].clientX;
        isDragging = true;
        slideList.style.transition = "none";
    });
    
    slideContainer.addEventListener("touchmove", function(e) {
        if (!isDragging) return;
        currentX = e.touches[0].clientX - startX;
        var offset = -currentIndex * 100 + (currentX / slideContainer.offsetWidth) * 100;
        slideList.style.transform = "translateX(" + offset + "%)";
    });
    
    slideContainer.addEventListener("touchend", function(e) {
        if (!isDragging) return;
        isDragging = false;
        slideList.style.transition = "transform 0.3s ease";
        
        if (Math.abs(currentX) > 50) {
            if (currentX > 0 && currentIndex > 0) {
                currentIndex--;
            } else if (currentX < 0 && currentIndex < totalImages - 1) {
                currentIndex++;
            }
        }
        
        slideList.style.transform = "translateX(-" + (currentIndex * 100) + "%)";
        updateDots(currentIndex);
        currentX = 0;
    });
    
    // 指示点点击
    $("#slide .bui-slide-head span").off("click").on("click", function() {
        var index = parseInt($(this).attr("data-index"));
        currentIndex = index;
        slideList.style.transform = "translateX(-" + (currentIndex * 100) + "%)";
        updateDots(currentIndex);
    });
}

// 渲染商品详情
function renderGoodsDetail(goods) {
    console.log("渲染商品详情:", goods);
    
    // 商品名称
    $("#goodsName").text(goods.goods_name || "商品名称");
    
    // 价格显示
    // discount 是打折后的真实价格（现价），amount 是打折前的原价
    var discountPrice = goods.discount || "0.00";
    var originalPrice = goods.amount || "0.00";
    
    // 格式化价格，确保显示两位小数
    discountPrice = parseFloat(discountPrice).toFixed(2);
    originalPrice = parseFloat(originalPrice).toFixed(2);
    
    // 显示现价（discount - 真实价格）
    $("#goodsDiscount").text(discountPrice);
    
    // 显示原价（amount - 打折前价格），如果原价和现价相同或原价为0，则隐藏原价
    if (originalPrice && parseFloat(originalPrice) > parseFloat(discountPrice)) {
        $("#goodsAmount").text(originalPrice);
        $("#goodsAmountContainer").show();
    } else {
        $("#goodsAmountContainer").hide();
    }
    
    // 销量（如果没有销量字段，可以显示0或隐藏）
    var sales = goods.sales || 0;
    $("#goodsSales").text(sales);
    
    // 描述
    $("#goodsDescription").text(goods.description || "暂无描述");
    
    // 商品图片 - 处理分号分隔的图片
    var imagesHtml = "";
    if (goods.goods_img) {
        var images = goods.goods_img.split(';');
        images.forEach(function(img) {
            img = img.trim();
            if (img) {
                var imgUrl = "";
                if (img.indexOf('http') === 0) {
                    imgUrl = img;
                } else {
                    imgUrl = API_BASE_URL + img;
                }
                imagesHtml += '<li><img src="' + imgUrl + '" alt="' + (goods.goods_name || '商品') + '" onerror="this.src=\'https://via.placeholder.com/300x300?text=Error\'"></li>';
            }
        });
    }
    
    if (imagesHtml) {
        // 立即设置轮播图容器的样式，避免闪烁
        var $slideMain = $("#slide .bui-slide-main");
        var $goodsImages = $("#goodsImages");
        
        // 确保样式已应用
        $slideMain.css({
            'overflow': 'hidden',
            'height': '100%',
            'position': 'relative'
        });
        $goodsImages.css({
            'display': 'flex',
            'height': '100%',
            'margin': '0',
            'padding': '0',
            'list-style': 'none',
            'transition': 'transform 0.3s ease',
            'transform': 'translateX(0)'
        });
        
        // 插入图片HTML
        $goodsImages.html(imagesHtml);
        
        // 立即设置每个li的样式
        $goodsImages.find('li').css({
            'height': '100%',
            'flex': '0 0 100%',
            'width': '100%'
        });
        
        // 生成指示点
        var imagesCount = goods.goods_img ? goods.goods_img.split(';').filter(function(img) { return img.trim(); }).length : 1;
        var dotsHtml = "";
        for (var i = 0; i < imagesCount; i++) {
            dotsHtml += '<span class="' + (i === 0 ? 'active' : '') + '" data-index="' + i + '"></span>';
        }
        $("#slide .bui-slide-head").html(dotsHtml);
        
        // 如果只有一张图片，隐藏指示点
        if (imagesCount <= 1) {
            $("#slide .bui-slide-head").hide();
        } else {
            $("#slide .bui-slide-head").show();
        }
        
        // 立即初始化轮播图（使用requestAnimationFrame确保DOM已渲染）
        requestAnimationFrame(function() {
            // 初始化轮播图（如果bui库可用）
            if (typeof bui !== 'undefined' && typeof bui.slide === 'function') {
                try {
                    var uiSlide = bui.slide({
                        id:"#slide",
                        height: 375,
                        autoplay: false, // 关闭自动播放，让用户手动滑动
                        autopage: false,
                        zoom: true,
                        loop: true, // 循环播放
                        onChange: function(index) {
                            // 更新指示点
                            $("#slide .bui-slide-head span").removeClass("active");
                            $("#slide .bui-slide-head span").eq(index).addClass("active");
                            console.log("轮播图切换到第", index + 1, "张");
                        }
                    });
                    console.log("轮播图初始化成功，共", imagesCount, "张图片");
                    
                    // 如果bui.slide不支持onChange，手动绑定指示点点击事件
                    $("#slide .bui-slide-head span").on("click", function() {
                        var index = $(this).attr("data-index");
                        if (uiSlide && typeof uiSlide.slideTo === 'function') {
                            uiSlide.slideTo(parseInt(index));
                        } else if (uiSlide && typeof uiSlide.switchTo === 'function') {
                            uiSlide.switchTo(parseInt(index));
                        }
                    });
                } catch(e) {
                    console.warn("bui.slide初始化失败:", e);
                    // 如果bui.slide失败，使用简单的原生滑动实现
                    initSimpleSlide();
                }
            } else {
                console.warn("bui.slide不可用，使用简单的滑动实现");
                // 使用简单的原生滑动实现
                initSimpleSlide();
            }
        });
    } else {
        $("#goodsImages").html('<li><img src="https://via.placeholder.com/300x300?text=No+Image" alt="暂无图片"></li>');
        // 即使只有一张图片，也设置样式
        $("#goodsImages").css({
            'display': 'flex',
            'height': '100%'
        });
        $("#goodsImages").find('li').css({
            'height': '100%',
            'flex': '0 0 100%',
            'width': '100%'
        });
    }
    
    // 简单的原生滑动实现（备用方案）
    function initSimpleSlide() {
        var slideContainer = document.querySelector("#slide .bui-slide-main");
        var slideList = document.querySelector("#goodsImages");
        if (!slideContainer || !slideList) return;
        
        var currentIndex = 0;
        var images = slideList.querySelectorAll("li");
        var totalImages = images.length;
        
        if (totalImages <= 1) return;
        
        // 设置容器为横向滚动
        slideList.style.display = "flex";
        slideList.style.transition = "transform 0.3s ease";
        slideContainer.style.overflow = "hidden";
        images.forEach(function(img) {
            img.style.flex = "0 0 100%";
            img.style.width = "100%";
        });
        
        // 触摸滑动支持
        var startX = 0;
        var currentX = 0;
        var isDragging = false;
        
        slideContainer.addEventListener("touchstart", function(e) {
            startX = e.touches[0].clientX;
            isDragging = true;
        });
        
        slideContainer.addEventListener("touchmove", function(e) {
            if (!isDragging) return;
            currentX = e.touches[0].clientX - startX;
        });
        
        slideContainer.addEventListener("touchend", function(e) {
            if (!isDragging) return;
            isDragging = false;
            
            if (Math.abs(currentX) > 50) {
                if (currentX > 0 && currentIndex > 0) {
                    currentIndex--;
                } else if (currentX < 0 && currentIndex < totalImages - 1) {
                    currentIndex++;
                }
            }
            
            slideList.style.transform = "translateX(-" + (currentIndex * 100) + "%)";
            updateDots(currentIndex);
            currentX = 0;
        });
        
        // 更新指示点
        function updateDots(index) {
            $("#slide .bui-slide-head span").removeClass("active");
            $("#slide .bui-slide-head span").eq(index).addClass("active");
        }
        
        // 指示点点击
        $("#slide .bui-slide-head span").on("click", function() {
            var index = parseInt($(this).attr("data-index"));
            currentIndex = index;
            slideList.style.transform = "translateX(-" + (currentIndex * 100) + "%)";
            updateDots(currentIndex);
        });
    }
    
    // 详情图片（如果有单独的详情图片字段，可以在这里添加）
    // 目前使用goods_img作为详情图
    if (goods.goods_img) {
        var detailImagesHtml = "";
        var images = goods.goods_img.split(';');
        images.forEach(function(img) {
            img = img.trim();
            if (img) {
                var imgUrl = "";
                if (img.indexOf('http') === 0) {
                    imgUrl = img;
                } else {
                    imgUrl = API_BASE_URL + img;
                }
                detailImagesHtml += '<img style="margin-top: -5px;" src="' + imgUrl + '" width="100%" alt="' + (goods.goods_name || '商品') + '" onerror="this.style.display=\'none\'">';
            }
        });
        $("#goodsDetailImages").html(detailImagesHtml);
    }
}

var fx;
var sortClick;
var searchGoods;
var currentGoodsId = null;

// 页面加载完成后获取商品详情
$(document).ready(function() {
    console.log("商品详情页DOM加载完成");
    loadGoodsDetail();
});

// 如果bui库可用，也执行bui相关初始化
if (typeof bui !== 'undefined' && typeof bui.ready === 'function') {
    bui.ready(function(){
        console.log("bui.ready 执行");
        
        // 获取当前商品ID（用于后续功能）
        currentGoodsId = getUrlParam('id');
        
        $("#commentGo").on("click",function(e){
            if (currentGoodsId) {
                bui.load({ url: "/index/index/comment?gid=" + currentGoodsId});
            }
        });

        $("#closedislog").on("click",function(e){
            if (typeof uiDialogFull !== 'undefined') {
                uiDialogFull.close();
            }
        });

        var uiDialogFull = bui.dialog({
            id: "#dialogFull",
            position: "top",
            fullscreen: true,
            useBox: true,
            buttons: []
        });

        fx = function(){
            if (!currentGoodsId) {
                bui.alert("商品ID不存在");
                return;
            }
            
            var uiLoading = bui.loading({
                appendTo:".bui-page",
                width: 40,
                height: 40,
                callback: function (argument) {
                    console.log("clickloading")
                }
            });
            uiLoading.show();
            
            // 获取商品信息用于分享
            var goodsName = $("#goodsName").text();
            var goodsPrice = $("#goodsDiscount").text();
            var goodsCover = "";
            var firstImg = $("#goodsImages img").first().attr("src");
            if (firstImg) {
                goodsCover = firstImg;
            }
            
            $.ajax({
                url: "/index/index/getQrcode",
                data: {
                   url: window.location.href,
                   name: goodsName,
                   price: goodsPrice,
                   cover: goodsCover
                },
                type: "post",
                dataType: "json",
                success: function(data){
                    uiLoading.stop();
                    if(data.status == 1){
                        copyText(data.url);
                    }else{
                        bui.alert(data.msg);
                    }
                },
                error: function(data){
                    uiLoading.stop();
                    bui.alert("分享失败");
                }
            });

            function copyText(text) {
                var oInput = document.createElement('input');
                oInput.value = text;
                document.body.appendChild(oInput);
                oInput.select();
                document.execCommand("Copy");
                oInput.className = 'oInput';
                oInput.style.display='none';
                bui.alert("已复制分享链接");
            }
        }

        $("#addShopCart").on("click",function(e){
            if (!currentGoodsId) {
                bui.alert("商品ID不存在");
                return;
            }
            var storage = bui.storage(0);
            storage.set("shopCart",{"gid":currentGoodsId},"gid");
            bui.hint({ content: "<i class='icon-check'></i><br />添加成功", position: "center", effect: "fadeInDown" });
        });

        $("#buyGoodsGo").on("click",function(e){
            if (!currentGoodsId) {
                bui.alert("商品ID不存在");
                return;
            }
            var gid = [currentGoodsId];
            bui.load({ url: "/index/index/buyGoods",param: {gid:JSON.stringify(gid)}});
        });
    });
} else {
    console.warn("bui库未加载，部分功能可能不可用");
}

$("#kflinksGo").on("click",function(e){
    var kflink = "https://plan.auth.sishuge.cn/index/index/home?visiter_id=&visiter_name=&avatar=&business_id=1&groupid=0&special=1";
    if(kflink){
        if (typeof bui !== 'undefined' && bui.load) {
            bui.load({ url: "/index/index/kflinks"});
        } else {
            window.location.href = kflink;
        }
    }else{
        if (typeof bui !== 'undefined' && bui.alert) {
            bui.alert("当前客服坐席无人值班");
        } else {
            alert("当前客服坐席无人值班");
        }
    }
});
</script>
<script type="text/javascript">
    // 获取当前商品ID的函数
    function getCurrentGoodsId() {
        return getUrlParam('id') || 0;
    }
    
    // 联系客服购买按钮点击事件
    function initContactServiceButton() {
        var contactBtn = document.getElementById('contactService');
        if (contactBtn) {
            contactBtn.addEventListener('click', function() {
                var goodsId = getCurrentGoodsId();
                // 跳转到聊天页面，带上商品ID
                window.location.href = './chat.html?goods_id=' + goodsId;
            });
        }
    }
    
    // 客服链接点击事件
    function initKefuLink() {
        $("#kflinksGo").off('click').on("click", function(e){
            e.preventDefault();
            var goodsId = getCurrentGoodsId();
            // 跳转到聊天页面
            window.location.href = './chat.html?goods_id=' + goodsId;
        });
    }
    
    // 页面加载完成后初始化
    $(document).ready(function() {
        initContactServiceButton();
        initKefuLink();
    });
    
    // 如果bui库可用，也在bui.ready中初始化
    if (typeof bui !== 'undefined' && typeof bui.ready === 'function') {
        bui.ready(function() {
            initContactServiceButton();
            initKefuLink();
        });
    }
</script>
</body>
</html>